package com.leetcode.q2;

/**
 * <p> description: desc</p>
 *
 * @author tanzc
 * @date 2022/3/29
 **/
public class TwoNumAdd {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ll1 = l1, ll2 = l2;
        ListNode ans;
        ListNode p = new ListNode();
        int l = 0, h = 0;
        ans = p;
        while (ll1 != null && ll2 != null) {
            int val = ll1.val + ll2.val + h;
            l = val % 10;
            h = val / 10;
            ListNode q = new ListNode(l);
            p.next = q;
            p = q;
            ll1 = ll1.next;
            ll2 = ll2.next;
        }
        ListNode t = null;
        if (ll1 != null) {
            t = ll1;
        } else if (ll2 != null) {
            t = ll2;
        }

        while (t != null) {
            if (h == 0) {
                p.next = t;
                break;
            }
            int val = t.val + h;
            l = val % 10;
            h = val / 10;
            ListNode q = new ListNode(l);
            p.next = q;
            p = q;
            t = t.next;
        }
        if (h != 0) {
            p.next = new ListNode(h);
        }
        return ans.next;
    }

    public void sout(ListNode l) {
        while (l != null) {
            System.out.print(l.val + " ");
            l = l.next;
        }
        System.out.println();
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

